package com.example.rab.config;

import com.example.rab.service.UserService;
import com.example.rab.utils.JwtUtils;
import com.example.rab.utils.R;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @projectName: Book
 * @package: com.example.bookdev.config
 * @className: JwtFilter
 * @author: zzh
 * @description: TODO
 * @version: 1.0
 */
@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    @Resource
    JwtUtils jwtUtil;

    @Resource
    UserService userService;



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求的URI
        String requestURI = request.getRequestURI();

        // 定义不需要JWT验证的路径集合
        List<String> unprotectedPaths = Arrays.asList("/wx/login", "/wx/register", "/wx/test");

        // 检查请求的路径是否在不需要JWT验证的路径集合中
        if (unprotectedPaths.stream().anyMatch(requestURI::startsWith)) {
            filterChain.doFilter(request, response); // 对不需要JWT验证的路径直接放行
            return;
        }

        String jwtToken = request.getHeader("token");//从请求头中获取token
        if (jwtToken != null && !jwtToken.isEmpty() && jwtUtil.checkToken(jwtToken)){
            try {
                //token可用
                Claims claims = jwtUtil.getTokenBody(jwtToken);
                String phone = (String) claims.get("phone");
                UserDetails user = userService.loadUserByUsername(phone);
                if (user != null){
                    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception e){
                log.error(e.getMessage());
            }
            filterChain.doFilter(request, response);//继续过滤
        }

    }
}